package org.lanqiao.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import org.apache.commons.lang.StringUtils;

/**
 * @Class：LatitudeUtils
 * @Description: //TODO
 * @auther: 刘金渝
 * @date: 2019/6/11 22:38
 * 用地址获取经纬度，
 */

public class LatitudeUtils {
    // 平均半径,单位：m
    private static final double EARTH_RADIUS = 6371393;

    public static final String KEY_1 = "7d9fbeb43e975cd1e9477a7e5d5e192a";
    // String key2 = "8ec6cd98bd56554407a207d597c0f3e5";
    // String key3 = "be025dc280e1e3f7ffb95fe42a01fab2";
    // String key4 = "327db7009617d6806b9c38e819ea06ac";

    /**
     * 返回输入地址的经纬度坐标
     * key lng(经度),lat(纬度)
     */
    public static String getGeocoderLatitude(String address) {
        BufferedReader in = null;
        try {
            //将地址转换成utf-8的16进制
            address = URLEncoder.encode(address, "UTF-8");
            URL tirc = new URL("http://api.map.baidu.com/geocoder?address=" + address + "&output=json&key=" + KEY_1);

            in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            String str = sb.toString();
            Map<String, String> map = null;
            if (StringUtils.isNotEmpty(str)) {
                int lngStart = str.indexOf("lng\":");
                int lngEnd = str.indexOf(",\"lat");
                int latEnd = str.indexOf("},\"precise");
                if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
                    String lng = str.substring(lngStart + 5, lngEnd);
                    String lat = str.substring(lngEnd + 7, latEnd);
                    map = new HashMap<String, String>();
                    //经度
                    map.put("lng", lng);
                    //纬度
                    map.put("lat", lat);
                    return lng+","+lat;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @Author 刘金渝
     * @Description //TODO
     * @Date 2019/6/12 0:22
     * @Param [longitude1, latitude1, longitude2, latitude2]
     * @explain       获取两点间的距离
     * @return double
     */

    public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        // 纬度
        double Lat1 = rad(latitude1);

        double Lat2 = rad(latitude2);
        //两点纬度之差
        double a = Lat1 - Lat2;
        //经度之差
        double b = rad(longitude1) - rad(longitude2);
        //计算两点距离的公式
        double s = 2 * Math.asin(Math

                .sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));

        //弧长乘地球半径（半径为米）
        s = s * 6378137.0;
        //精确距离的数值
        s = Math.round(s * 10000d) / 10000d;

        return s;

    }



    private static double rad(double d) {
        //角度转换成弧度
        return d * Math.PI / 180.00;

    }


    public  static double[] std(String ip){
        String []ips=ip.split(",");
        double[]dds=new double[ips.length];
        for (int i = 0; i <ips.length ; i++) {
            double d = Double.parseDouble(ips[i]);
            dds[i]=d;
        }
        return dds;
    }
    /**
     * @Author 刘金渝
     * @Description //TODO
     * @Date 2019/6/12 0:56
     * @Param [unsortMap]
     * @explain       对集合进行排序
     * @return java.util.Map<K,V>
     */


    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> unsortMap) {

        List<Map.Entry<K, V>> list =
                new LinkedList<Map.Entry<K, V>>(unsortMap.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }

        return result;

    }

    public static Object getKey(Map map, Object value){
        List<Object> keyList = new ArrayList<>();
        for(Object key: map.keySet()){
            if(map.get(key).equals(value)){
                keyList.add(key);
            }
        }
        return keyList;
    }
}